package cn.regexp.marktag.action;

import cn.regexp.marktag.decorator.CoreFileDecorator;
import cn.regexp.marktag.utils.CoreFileUtils;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import static com.intellij.openapi.actionSystem.CommonDataKeys.VIRTUAL_FILE_ARRAY;

/**
 * @author Regexpei
 * @date 2024/5/1 12:58
 * @description
 */
public class CoreFileAction extends AnAction {

    @Override
    public void actionPerformed(@NotNull AnActionEvent actionEvent) {
        Project project = actionEvent.getProject();
        if (project == null) {
            return;
        }

        DataContext dataContext = actionEvent.getDataContext();
        // 获取操作的文件/目录
        VirtualFile[] virtualFiles = VIRTUAL_FILE_ARRAY.getData(dataContext);
        if (virtualFiles == null) {
            return;
        }


        List<VirtualFile> virtualFileList = new ArrayList<>();
        for (VirtualFile virtualFile : virtualFiles) {
            // 如果是目录，则遍历获取所有文件
            if (virtualFile.isDirectory()) {
                CoreFileUtils.collectFiles(virtualFile, virtualFileList);
            } else {
                virtualFileList.add(virtualFile);
            }
        }

        String projectName = project.getName();
        // 获取文件的相对路径
        List<String> coreFiles = virtualFileList.parallelStream()
                .map(item -> item.getPath().split(projectName)[1])
                .toList();

        // 将文件路径写入缓存
        CoreFileDecorator.CACHE.get(projectName).addAll(coreFiles);
        // 将文件路径写到核心文件里
        CoreFileUtils.writeFile(project, coreFiles);
    }

}
